package com.itheima.filter.getewayfilter;

import com.itheima.common.utils.JwtUtils;
import com.itheima.common.utils.RequestContext;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

@Component
public class UserServiceGatewayFilterFactory extends AbstractGatewayFilterFactory{


    /**
     * 局部拦截器
     * @param config
     * @return
     */
    @Override
    public GatewayFilter apply(Object config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //获取令牌
                ServerHttpRequest request = exchange.getRequest();
                ServerHttpResponse response = exchange.getResponse();

                String token = request.getHeaders().getFirst("token");
                //解析令牌,判断令牌的flag是否为1（用户登录）,0未登录
                if (token == null || JwtUtils.checkToken(token) || RequestContext.getNode("flag")==null) {
                    //拦截
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    return response.writeWith(Flux.just(response.bufferFactory().wrap("身份无效，请先登录！".getBytes(Charset.forName("UTF-8")))));
                }
                Integer flag = RequestContext.getNodeValue("flag");
                //如果flag=0，拦截请求
                if (flag == 0){

                }

                return null;
            }
        };
    }
}
